//author:

define(['butterfly/notification', 'butterfly/task/Task', 'butterfly/task/TaskQueue','main/DownloadManager', 'view!main/dialog/dialog'], function(Notification, Task, TaskQueue,DownLoad, Dialog) {

  var AjaxTask = Task.extend({

    constructor: function(url) {
      this.url = url;
    },

    execute: function(success, fail) {
      var me = this;
      var params = {
        url: this.url,

        success: function(ajaxCont) {
          var result = JSON.parse(ajaxCont)
          success(result);
        },
        error: fail
      }

      this.ajax = $.ajax(params);

    },

    abort: function() {
      this.ajax.abort();
    }

  });

  var DownloadModuleTask = Task.extend({
      appkey: '65995a05f3bdb7cf90bcab98f03b7b05',
      serverUrl :'http://115.28.1.119:18860',
      storageDirectory: function() {
        return (device.platform == 'iOS') ? cordova.file.documentsDirectory : cordova.file.externalDataDirectory;
      },

      wwwDirecotry: function() {
        return this.storageDirectory() + (device.platform == 'iOS' ? 'app/' : 'www/');
      },

      constructor: function(fs, module) {
        this.fs = fs;
        this.module = module;
      },
      execute: function(success, fail) {

        var url ='http://115.28.1.119:18860/mam/api/mam/clients/files/' + this.module.bundle + '?appkey=' + this.appkey;
        var target = this.wwwDirecotry() + this.module.identifier + '.zip';
        var me = this;
        DownLoad.onDownload(
          this.module.identifier, url, this.module.identifier, target,
          function(identifier, progress) {
            //emmit onprogress event
            // me.trigger('progress', identifier, progress);
          },
          function(url, filename, entry) {
            console.log('DownLoad success');

            zip.unzip(target, me.wwwDirecotry() + me.module.identifier + '/', function() {
              console.log('unzip success');//android 不要加sdc;ard
              // 包名加路径(android路径);
              // var devicePath = (device.platform =='iOS')?'app/'+entry.name: "com.foss.bsl/app/"+entry.name;
              DownLoad.removeTask(me.module.identifier);//删除下载缓存记录；
              DownLoad.saveState();
              me.fs.getFile(entry.name, {}, function(f) {

                f.remove(function() {
                  success();

                }, fail); //remove

              }, function(error){
                console.log('压缩包删除失败');
              }); //

            }); //unzip

          }, function(){
            fail();
            console.log('下载失败')
          });
      },

      abort: function() {

      }
    });


  var ModuleManager = function() {
    this.serverInfo = {
      'appKey': '65995a05f3bdb7cf90bcab98f03b7b05',
      'secret': '93f53d4c-d326-4268-af12-e08778b152ca'
    }
    this.serverUrl = 'http://115.28.1.119:18860';
    this.identifier = 'com.foreveross.atom';
    // 115.28.1.119:18860/
  }

  _.extend(ModuleManager.prototype, {

    storageDirectory: function() {
      return (device.platform == 'iOS') ? cordova.file.documentsDirectory : cordova.file.externalDataDirectory;
    },

    wwwDirecotry: function() {
      return this.storageDirectory() + (device.platform == 'iOS' ? 'app/' : 'www/');
    },

    errorHandler: function(e) {
      var msg = '';

      switch (e.code) {
        case FileError.QUOTA_EXCEEDED_ERR:
          msg = 'QUOTA_EXCEEDED_ERR';
          break;
        case FileError.NOT_FOUND_ERR:
          msg = 'NOT_FOUND_ERR';
          break;
        case FileError.SECURITY_ERR:
          msg = 'SECURITY_ERR';
          break;
        case FileError.INVALID_MODIFICATION_ERR:
          msg = 'INVALID_MODIFICATION_ERR';
          break;
        case FileError.INVALID_STATE_ERR:
          msg = 'INVALID_STATE_ERR';
          break;
        default:
          msg = 'Unknown Error';
          break;
      };

      console.log('Error: ' + msg);
    },

    getPrivellege: function(username, callback) {
      var url = this.serverUrl + "/mam/api/mam/clients/apps/" + this.identifier + "/" + username +"/auth?appKey=" + this.serverInfo.appKey;
      $.ajax({
        url: url,
        method: 'GET',
      }).success(function(data) {
        console.log(data);
        callback && callback(data);
      }).error(function() {

      });
    },

    //检查应用程序更新
    checkAppUpdate:function(success,fail){
      var me = this;
      if (!window.cordova) return;
      me.getAppVersion(function(remoteVersion){
        navigator.appInfo.getVersion(function(localVersion){
          // localVersion = "2.5.0";
          if(remoteVersion>localVersion){
            success();
          }else{
            fail();
          }
        })
      },function(){
        fail();
      });
    },
    checkUpdate: function(success, fail) {
      if (!window.cordova) return;

      console.log('checkUpdate...');

      var me = this;

      var task = 2;
      var localModules, remoteModules;
      this.getLocalModulesInfo(function(modules) {
        localModules = modules;
        // console.log("got local: %s", JSON.stringify(localModules));
        if (--task == 0) {
          var diff = me.diffModules(localModules, remoteModules);
          success(diff);
        };
      }, fail);

      this.getLastestModulesFromServer(function(modules) {
        remoteModules = modules;
        // console.log("got remote: %s", JSON.stringify(remoteModules));

        if (--task == 0) {
          var diff = me.diffModules(localModules, remoteModules);
          success(diff);
        };
      }, fail);
    },
    //对比两个模块信息数组，返回可更新的模块数组
    diffModules: function(local, remoteModules) {
      var diff = [];
      //<identifier, module>的映射，方便下面一步过滤使用
      var localModulesMapping = _.object(_.map(local, function(module) {
        return module.identifier;
      }), local);
      //过滤掉不需要更新的模块
      var updatableModuleArray = _.filter(remoteModules, function(remoteModule) {
        //根据远程模块的identifier，尝试找出相应的本地模块
        var localModule = localModulesMapping[remoteModule.identifier];
        //有同样identifier的本地模块存在，且版本号不相同，返回远程模块信息。
        return localModule && (localModule.version < remoteModule.version) || !localModule;
      });
      return updatableModuleArray;
    },

    //获取本地模块信息
    getLocalModulesInfo: function(success, fail) {

      console.log('getLocalModulesInfo');

      var me = this;
      window.resolveLocalFileSystemURL(me.wwwDirecotry(), function(fs) {

        console.log('local.resolveLocalFileSystemURL');

        var dirReader = fs.createReader();
        dirReader.readEntries(function(entries) {

          var packageJSONArray =
            _.chain(entries)
            .filter(function(entry) {
              return entry.isDirectory;
            })
            .value();

          me.loadModulesInfoFromDirectories(fs, packageJSONArray, function(moduleNameArray) {

            var moduleInfoArray = _.map(moduleNameArray, function(moduleName) {
              return me.wwwDirecotry() + moduleName + '/package.json';
            });

            console.log(moduleInfoArray)

            //AJAX 队列
            var q = new TaskQueue();
            moduleInfoArray.forEach(function(json) {
              var task = new AjaxTask(json);
              q.add(task);
            });
            var jsonArray = [];

            q.success(function(arr) {
              me.dependenciesModules(arr,function(newArr){//处理依赖
                success(newArr);
              });

            });

            q.fail(function(error) {
              console.log(error);
              Notification.show({
                type: 'error',
                message: "读取本地模块信息失败"
              });
            });

            q.execute();
          });



        }, fail);
      });

    },

    //给出一个文件夹列表，返回（回调方式）文件夹数组
    loadModulesInfoFromDirectories: function(fs, folderEntries, success) {

      var result = [];
      var tasks = folderEntries.length;
      folderEntries.forEach(function(folderEntry) {
        fs.getFile(folderEntry.name + '/package.json', {
          create: false
        }, function(fileEntry) {
          //TODO: 把结果存到result
          result.push(folderEntry.name);
          if (--tasks == 0) success(result);
        }, function() {
          if (--tasks == 0) success(result);
        });
      });
    },

    //从服务器获取最新模块信息。
    getLastestModulesFromServer: function(success, fail) {

      var me = this;
      this.getAppTokenFromServer(function(token) {
        me.getModulesInfoFromServer(token, success, fail);
      }, fail);
    },

    //获取应用token
    getAppTokenFromServer: function(success, fail) {
      var me = this;
      if(typeof cordova !=="undefined"){
          if(device.platform =='iOS'){
            me.platform='ios';
          }else{
            me.platform='android';
          }
          navigator.appInfo.getVersion(function(args) {
            // args = "2.5.0";
            $.ajax({
              type: 'post',
                url: me.serverUrl + '/mam/api/mam/clients/apps/'+me.platform+'/' + me.identifier + '/' + args + '/validate',
                data: me.serverInfo,
                success: function(serverResult) {
                  success(serverResult.token);
                },
                error: fail
              })
          });
      }else{
        fail();
      }
      // me.getAppVersion(function(appVersion){
      //  $.ajax({
      //    type: 'post',
      //      url: me.serverUrl + '/mam/api/mam/clients/apps/android/cn.com.changan.ichangan/' + appVersion + '/validate',
      //      data: me.serverInfo,
      //      success: function(serverResult) {
      //        success(serverResult.token);
      //      },
      //      error: fail
      //    })
      // },fail);

    },
    // //获取上架的应用版本号
    getAppVersion:function(getAppVersionSuccess,fail){
      var me = this;
      var platform;

      if(typeof cordova !== 'undefined'){
          if(device.platform =='iOS'){
            me.platform='ios';
          }else{
            me.platform='android';
          }
        }

      $.ajax({
        type: 'get',
        url: me.serverUrl + '/mam/api/mam/clients/update/'+me.platform+'/' +me.identifier+ '/',
        data:{
          'appKey':me.serverInfo.appKey
        },
        success: function(appInfo) {
          if(appInfo){
            getAppVersionSuccess(appInfo.version);
          }
        },
        error: fail
      })
    },
    //获取模块信息
    getModulesInfoFromServer: function(token, success, fail) {
      var me = this;
      $.ajax({
        type: 'get',
        url: me.serverUrl + '/mam/api/mam/clients/apps/modules/' + token,
        data: {
          'timeStamp': new Date().getTime(),
        },
        success: function(ModelResult) {
          success(ModelResult.modules);
        },
        error: fail
      })
    },
    dependenciesModules:function(arr,success){
      var newArr= _.clone(arr);
      //提取依赖模块信息，再与本地模块合并成一个新的数组；
              _.each(newArr, function(item) {
                if (_.keys(item.dependencies).length > 0) { //如果模块中有依赖，再与本地模拟对比版本号;
                  var obj = { //先将依赖转换为对象
                    'identifier': _.keys(item.dependencies)[0],
                    'version': _.values(item.dependencies)[0]
                  };
                  _.each(arr, function(localItem,k) { //再次遍历本地模块数组
                    if (localItem.identifier === obj.identifier && localItem.version < obj.version) {
                      delete newArr[k];//如果在依赖模块，在本地模块信息数组中有，则对比，如果本地的版本低于依赖的，则删除本地的，添加依赖。
                      newArr.push(obj);
                    }
                  });
                }
              });
          success(_.compact(newArr));
    },
    deleteModel:function(moduleName, callback){//模块删除
            var directoryName = moduleName;
            var me = this;
            if(!this.isAllow(moduleName, 'DELETE')) {
              return new Notification({
                message: '当前模块无权限卸载',
                type: 'error'
              }).show();
            }

            var _this = this;

            new Dialog({
              ok: request,
              message: "你确定要删除当前模块吗?"
            }).show();

            function request() {
              window.resolveLocalFileSystemURL(me.wwwDirecotry() + moduleName , function(fs) {
                fs.removeRecursively(function(){
                    new Notification({
                      type: 'info',
                      message: '模块卸载成功'
                    }).show();
                    callback && callback()
                },function(error){
                  console.log(error)
                });
              })
            }
            return;

            if(window.cordova){
              navigator.notification.confirm(
                ("是否删除此模块"), // message
                function(button){
                  if (button == "1" || button == 1) {
                          $.ajax({
                            url: 'http://bsl.foreveross.com/mam/api/mam/clients/apps/' + me.identifier +'/guest/auth',
                            data: {
                              'appKey': '9ac10bdf29e6cf120294703c95a60878'
                            },
                            success: function(priviligesResult) {
                              var priviligesModulesArray = _.groupBy(priviligesResult.priviliges, function(value) {
                                return value[1];
                              }); //权限分组（根据模块名）;
                              var priviligesModules = _.keys(priviligesModulesArray); //拿取有读取权限的模块数组;
                              if(_.contains(priviligesModules,directoryName)){
                                var priviligesGet = priviligesModulesArray[directoryName];
                                var allow =_.find(priviligesGet,function(item){
                                  return item[0]=='UNAVAILABLE';
                                })

                                if(allow!=undefined){
                                    navigator.notification.alert(
                                      '此模块无法删除',  // 显示信息
                                      function(){},         // 警告被忽视的回调函数
                                      '提示',            // 标题
                                      '确定'                  // 按钮名称
                                  );
                                }else{
                                    window.resolveLocalFileSystemURL(me.wwwDirecotry() + directoryName , function(fs) {
                                      fs.removeRecursively(function(){
                                          navigator.notification.alert(
                                              '删除成功，请重启应用。',  // 显示信息
                                              function(){},         // 警告被忽视的回调函数
                                              '提示',            // 标题
                                              '确定'                  // 按钮名称
                                          );
                                          window.history.go(-1);
                                      },function(error){
                                        console.log(error)
                                      });
                                    })
                                }

                              }else{
                                navigator.notification.alert(
                                      '此模块无法删除',  // 显示信息
                                      function(){},         // 警告被忽视的回调函数
                                      '提示',            // 标题
                                      '确定'                  // 按钮名称

                                  );
                              }


                            }
                          })
                  }
                }, // callback
                '提示', // title
                '确定,取消' // buttonName
              );
            }

    },
    downloadModules:function(modulesArray, callback){//下载，更新模块；队列；
          var me = this;

        //提示
        me.loadingNotification = Notification.show({
          autoDismiss: false,
          showSpin: true,
          message: "正在下载中..."
        });

        function errorHandler(error) {
          console.error(error);
        }
        window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;

        window.resolveLocalFileSystemURL(me.wwwDirecotry(), function(fs) {

          var q = new TaskQueue();

          modulesArray.forEach(function(module) {
            var task = new DownloadModuleTask(fs, module);
            // me.listenTo(task, 'progress', me.onProgress);
            q.add(task);
          });

          q.success(function() {
            console.log('queue success');
            Notification.show({
              type: 'info',
              message: '模块下载完成'
            });
            me.loadingNotification.remove(); //删除压缩包后，提示成功，删除提示。
            callback('success');
          //         // navigator.notification.alert(
          //         //      '成功！请重新打开应用体验最新版本。',  // message
          //         //     function(){
          //         //      window.sessionStorage.setItem('updateCompleteModules',JSON.stringify(modulesArray));//更新完成的模块，存储起来，等待应用重启
          //         //      window.localStorage.setItem('updateCompleteTime',new Date().getTime());//更新完成时间
          //         //      window.history.go(-1);
          //         //      navigator.ResetWebview.reset();//清理缓存
          //         //     },         // callback
          //         //     '更新完成',            // title
          //         //     '确定'                  // buttonName
          //         // );
          //    var  d=dialog.createDialog({
          //               autoOpen: false, //默认为true
          //               closeBtn: false,
          //               buttons: {
          //                   '确定': function(){
          //                       window.sessionStorage.setItem('updateCompleteModules',JSON.stringify(modulesArray));//更新完成的模块，存储起来，等待应用重启
          //                       window.localStorage.setItem('updateCompleteTime',new Date().getTime());//更新完成时间
          //                       window.history.go(-1);
          //                       navigator.ResetWebview.reset();//清理缓存
          //                       this.close(); //所有逻辑必须放在关闭之前
          //                   }
          //               },
          //               content:'成功！请重新打开应用体验最新版本。',
          //               title:'更新完成'
          //           });
          // d.open();

          });

          q.fail(function(error) {
            callback('fail');
            me.loadingNotification.remove();
            Notification.show({
              type: 'error',
              message: "下载失败"
            });
          });

          q.execute();

        });
    },

    isAllow: function(identifier, operation) {
      if(!this.privellege) return false;
      return _.find(this.privellege, function(p) {
        return p[1] === identifier && p[0] == operation;
      })
    },

  });
  return ModuleManager;

})
